import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:schoollifedemo/business/personal/viewmodel/personal_friend_circle_edit_page_viewmodel.dart';
import 'package:schoollifedemo/commonwidget/button_widget.dart';
import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/common_dialog.dart';
import 'package:schoollifedemo/commonwidget/common_friend_circle_message_widget.dart';
import 'package:schoollifedemo/commonwidget/error_widget.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget_with_overflow.dart';
import 'package:schoollifedemo/entity/Entity.dart';
import 'package:schoollifedemo/localization/local_text.dart';

class PersonalFriendCircleEditPage extends BaseStatefulPage {
  const PersonalFriendCircleEditPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _PersonalFriendCircleEditPageState();
  }
}

class _PersonalFriendCircleEditPageState
    extends BasePageState<PersonalFriendCircleEditPage> {
  final PersonalFriendCircleEditPageViewModel _viewModel =
      PersonalFriendCircleEditPageViewModel();
  ScrollController? _scrollController;

  String commitText = '';
  Color defaultColor = const Color(0x66D0E7FF);
  Color downColor = const Color(0x662A84E7);

  @override
  void initState() {
    _viewModel.init();
    _viewModel.pullFriendCircleMessageList(
      onFailure: (msg) {
        DialogUtils.showTitleAndMessageDialog(
          context,
          clickOutSideDismiss: true,
          title: '错误',
          msg: msg,
        );
      },
    );

    _scrollController = ScrollController();
    _scrollController?.addListener(() {
      if (_scrollController?.position.pixels ==
          _scrollController?.position.maxScrollExtent) {
        // 是否到了底部，到了底部进行刷新
        _viewModel.pullFriendCircleMessageList(
            currentPage: (_viewModel.messageResp?.currentPage ?? 0) + 1,
            onFailure: (msg) {
              DialogUtils.showTitleAndMessageDialog(
                context,
                clickOutSideDismiss: true,
                title: "错误",
                msg: "result error pull FriendCircleMessageList: $msg",
              );
            });
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      initialData: CommonLoadingState.loading,
      stream: _viewModel.loadingState,
      builder: (buildContext, snapshot) {
        final loadingState = snapshot.data as CommonLoadingState?;
        switch (loadingState) {
          case CommonLoadingState.loading:
            return _loadingWidget();
          case CommonLoadingState.successTypeOne:
          case CommonLoadingState.successTypeTwo:
            return _bodyWidget();
          default:
            return _errorWidget();
        }
      },
    );
  }

  Widget _bodyWidget() {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: ListView(
          controller: _scrollController,
          physics: const BouncingScrollPhysics(),
          children: [
            const TextWidgetWithOverflow(
              HomeLocalText.yourFriendCircle,
              textAlign: TextAlign.left,
              insideColor: Colors.white,
              paddingLeft: 20,
              fontSize: 28,
              fontWeight: FontWeight.w400,
              paddingTop: 20,
            ),
            Offstage(
              offstage: _viewModel.messageResp?.messageList?.isEmpty == true,
              child: ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (buildContext, index) {
                  FriendCircleMessage? friendCircleMessage =
                      _viewModel.messageResp?.messageList?[index];
                  return GestureDetector(
                    onTapUp: (details) {
                      friendCircleMessage?.defaultColor = defaultColor;
                      setState(() {});
                    },
                    onTapDown: (details) {
                      friendCircleMessage?.defaultColor = downColor;
                      setState(() {});
                    },
                    onLongPress: () {
                      _showFriendCircleDialog(index, friendCircleMessage);

                      setState(() {
                        friendCircleMessage?.defaultColor = defaultColor;
                      });
                    },
                    child: CommonFriendCircleMessageWidget(
                      friendCircleMessage,
                      defaultInsideColor: friendCircleMessage?.defaultColor,
                      onCommitClick: () {
                        _viewModel.onCommit(context, index);
                      },
                      onLoveClick: () {
                        _viewModel.onLove(context, index);
                      },
                      onUnLoveClick: () {
                        _viewModel.onUnLove(context, index);
                      },
                      onCommitItemClick: (context, commitIndex) {
                        _showCommitDialog(
                          index,
                          commitIndex,
                          friendCircleMessage,
                        );
                      },
                    ),
                  );
                  // return Container();
                },
                separatorBuilder: (buildContext, index) {
                  return const SizedBox(
                    height: 10,
                  );
                },
                itemCount: _viewModel.messageResp?.messageList?.length ?? 0,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _showFriendCircleDialog(
    int index,
    FriendCircleMessage? friendCircleMessage,
  ) {
    DialogUtils.showSimpleCupertinoDialog(
      context,
      clickOutSideDismiss: true,
      widgets: Column(
        children: [
          ButtonWidget(
            insideWidget: const TextWidgetWithOverflow(
              '删除该朋友圈',
              fontSize: 14,
              insideColor: Colors.transparent,
              textColor: Colors.white,
            ),
            width: double.infinity,
            onButtonClick: () {
              // 删除评论
              Navigator.pop(context);
              _viewModel.deleteFriendCircle(
                conversationId: friendCircleMessage?.conversationId ?? '',
              );
            },
          ),
        ],
      ),
    );
  }

  void _showCommitDialog(
    int index,
    int commitIndex,
    FriendCircleMessage? friendCircleMessage,
  ) {
    DialogUtils.showSimpleCupertinoDialog(
      context,
      clickOutSideDismiss: true,
      widgets: Column(
        children: [
          Offstage(
            offstage: _viewModel.messageResp?.messageList?[index]
                    .commitList?[commitIndex]?.commitUser?.account !=
                _viewModel.getApplication().getLoginAccount(),
            child: ButtonWidget(
              insideWidget: const TextWidgetWithOverflow(
                '删除评论',
                fontSize: 14,
                insideColor: Colors.transparent,
                textColor: Colors.white,
              ),
              width: double.infinity,
              onButtonClick: () {
                // 删除评论
                Navigator.pop(context);
                String? conversationId = friendCircleMessage?.conversationId;
                String? commitId =
                    friendCircleMessage?.commitList?[commitIndex]?.commitId;
                _viewModel.deleteCommit(
                  conversationId: conversationId ?? '',
                  commitId: commitId ?? '',
                );
              },
            ),
          ),
          ButtonWidget(
            insideWidget: const TextWidgetWithOverflow(
              '评论该评论',
              fontSize: 14,
              textColor: Colors.white,
              insideColor: Colors.transparent,
            ),
            width: double.infinity,
            onButtonClick: () async {
              // 对评论进行评论
              Navigator.pop(context);
              Future.delayed(
                const Duration(microseconds: 500),
                () {
                  DialogUtils.showEditCommitDialog(
                    context,
                    onBackClick: () {
                      Navigator.pop(context);
                    },
                    onCancelClick: () {
                      Navigator.pop(context);
                    },
                    onConfirmClick: () {
                      String? conversationId =
                          friendCircleMessage?.conversationId;
                      String? toWho = friendCircleMessage?.account;
                      _viewModel.commitToWhoCommit(
                        conversationId: conversationId ?? '',
                        toWho: toWho ?? '',
                        msg: commitText,
                      );
                    },
                    onTextChange: (text) {
                      commitText = text;
                    },
                  );
                },
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _errorWidget() {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: CommonErrorWidget(
          '错误重试',
          onButtonClick: () async {
            _viewModel.pullFriendCircleMessageList();
          },
        ),
      ),
    );
  }

  Widget _loadingWidget() {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: const LoadingWidget(),
      ),
    );
  }
}
